import { isEqual } from 'lodash-es';
import { getAutoRefreshOptions } from './refreshDataMixin';
import refreshDataMixin from './refreshDataMixin';

export default function (option) {
  /*
   *  option: {
   *     area_code($store) {
   *       return $store.state.areaTree.activeAreaCode;
   *     }
   *  }
   * */
  const [key] = Object.keys(option);
  return {
    mixins: [refreshDataMixin],
    data() {
      return {
        autoRefreshOptions: Object.assign(getAutoRefreshOptions(), {
          paramsChecker: (params) => {
            const v = params && params[key];
            return v !== undefined && v !== null && v !== '';
          },
        }),
      };
    },
    computed: {
      [key]: function () {
        return option[key](this.$store);
      },
      apiParams() {
        return { [key]: this[key] };
      },
    },
    watch: {
      apiParams: {
        immediate: true,
        deep: true,
        handler(apiParams, oldParams) {
          if (!apiParams || !apiParams[key] || isEqual(apiParams, oldParams)) {
            return;
          }
          this.autoRefreshData();
        },
      },
    },
  };
}
